package ru.reinvent.perspectiva.fragments;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;

import ru.reinvent.perspectiva.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class OfferFragment extends SherlockFragment 
	{
	protected static final int IMAGE_CHOSEN = 0;
	protected static final int PHOTO_TAKEN = 1;
	
	protected final String IMAGE_TMP_FILE = "tmp.png";
	protected final int IMAGE_MAX_SIZE = 120;
	protected final int IMAGE_MAX_SIZE_HEIGHT = 90;
	protected final int IMAGE_SEND_MAX_SIZE = 840;
	
	protected View content;
	protected Menu menu;
	protected Uri lotPhotoUri;
	protected Context ctx;
	
	public OfferFragment() {;}
	
	@Override
	public void onCreate(Bundle savedInstanceState)
		{
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
		}
	
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) 
    	{
    	super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.offer_menu, menu);
        this.menu = menu;
        
        for (int i=0; i<menu.size(); i++) 
        	{
        	if (menu.getItem(i).getItemId() == R.id.menu_remove_photo) 
        		{
        		menu.getItem(i).setVisible(false);
        		menu.getItem(i).setEnabled(false);
        		}
        	}
    	}

	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
		{
		this.ctx = getActivity();
		if (content != null) 
			{
			if (content.getParent() != null) ((ViewGroup) content.getParent()).removeView(content);
			return content;
			}
		
		content = inflater.inflate(R.layout.offer_fragment, container, false);
		return content;
		}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) 
		{
		switch (item.getItemId())
			{
			case R.id.menu_submit: buildAndSendEmail(); break;
			case R.id.menu_add_photo: showChoosePhotoDialog(); break;
			case R.id.menu_remove_photo: 
				lotPhotoUri = null;
				content.findViewById(R.id.offer_photo_block).setVisibility(View.GONE);
				
        		item.setVisible(false);
        		item.setEnabled(false);

		        for (int i=0; i<menu.size(); i++) 
		        	{
		        	if (menu.getItem(i).getItemId() == R.id.menu_add_photo) 
        				{
		        		menu.getItem(i).setVisible(true);
		        		menu.getItem(i).setEnabled(true);
		        		break;
        				}
		        	}
				
				break;
			}
		
		return super.onOptionsItemSelected(item);
    	} 

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) 
		{
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode != Activity.RESULT_OK) return; 

		File imgFile = null;
		switch (requestCode)
			{
			case IMAGE_CHOSEN:
				try
					{
					lotPhotoUri = data.getData();

					String[] proj = { MediaStore.Images.Media.DATA };
					Cursor c = ctx.getContentResolver().query(lotPhotoUri,proj,null,null,null);
					if (c == null) 
						{
						Toast.makeText(ctx, R.string.toast_failed_to_add_photo,Toast.LENGTH_LONG).show();
						return;
						}
					
					c.moveToFirst();
					imgFile = new File(c.getString(c.getColumnIndex(MediaStore.Images.Media.DATA)));
					c.close();
					}
				catch(Exception e)
					{
					lotPhotoUri = null;
					Toast.makeText(ctx, R.string.toast_failed_to_add_photo,Toast.LENGTH_LONG).show();
					return;
					}
				break;
				
			case PHOTO_TAKEN:
				imgFile = new File(ctx.getFilesDir(),IMAGE_TMP_FILE);
				lotPhotoUri = Uri.fromFile(imgFile);
				break;
			}

		final Bitmap bmp = decodeFile(imgFile,true);
		if (bmp == null)
			{
			Toast.makeText(ctx,R.string.toast_failed_to_add_photo,Toast.LENGTH_LONG).show();
			return;
			}
		
        for (int i=0; i<menu.size(); i++) 
        	{
        	if (menu.getItem(i).getItemId() == R.id.menu_remove_photo) 
    			{
        		menu.getItem(i).setVisible(true);
        		menu.getItem(i).setEnabled(true);
    			}
        	else if (menu.getItem(i).getItemId() == R.id.menu_add_photo) 
				{
        		menu.getItem(i).setVisible(false);
        		menu.getItem(i).setEnabled(false);
				}
        	}

        ((ImageView) content.findViewById(R.id.offer_photo)).setImageBitmap(bmp);
        ((TextView) content.findViewById(R.id.offer_photo_path)).setText(imgFile.getName());
        content.findViewById(R.id.offer_photo_block).setVisibility(View.VISIBLE);
		}

	private void buildAndSendEmail()
		{
		final String text = buildEmailText();
		if (text == null)
			{
			Toast.makeText(ctx,R.string.toast_fill_in_fields, Toast.LENGTH_LONG).show();
			return;
			}
		
		final String[] recipients = { ctx.getResources().getString(R.string.offer_target_email) };
		final String subject = ctx.getResources().getString(R.string.offer_target_subject);
		
		final Intent emailIntent = new Intent(Intent.ACTION_SEND);
		emailIntent.setType("plain/text");
		emailIntent.putExtra(Intent.EXTRA_EMAIL,recipients);
		emailIntent.putExtra(Intent.EXTRA_SUBJECT,subject);
		emailIntent.putExtra(Intent.EXTRA_TEXT,text);
		if (lotPhotoUri != null) emailIntent.putExtra(Intent.EXTRA_STREAM, lotPhotoUri);

		startActivity(emailIntent);
		}
	
	private String buildEmailText() 
		{
		final Resources r = ctx.getResources();
		final StringBuilder emailText = new StringBuilder();
		
		final String name = ((EditText) content.findViewById(R.id.offer_name)).getText().toString();
		final String phone = ((EditText) content.findViewById(R.id.offer_phone_number)).getText().toString();
		final String vendor = ((EditText) content.findViewById(R.id.offer_vendor)).getText().toString();
		final String model = ((EditText) content.findViewById(R.id.offer_model)).getText().toString();
		final String year = ((EditText) content.findViewById(R.id.offer_buy_year)).getText().toString();
		final String sum = ((EditText) content.findViewById(R.id.offer_sum)).getText().toString();
		final int offerCheckR = ((CheckBox) content.findViewById(R.id.offer_check)).isChecked() ? R.string.lbl_yes : R.string.lbl_no;
		
		if (name.length()<3 || phone.length()<7 || vendor.length()<2 || model.length()<2 || year.length()<2 || sum.length()==0)
			return null;
		
		emailText.append(r.getString(R.string.offer_hint_name)+": ");
		emailText.append(name + "\n");
		emailText.append(r.getString(R.string.offer_hint_number)+": ");
		emailText.append(phone + "\n");
		emailText.append(r.getString(R.string.offer_hint_vendor)+": ");
		emailText.append(vendor + "\n");
		emailText.append(r.getString(R.string.offer_hint_model)+": ");
		emailText.append(model + "\n");
		emailText.append(r.getString(R.string.offer_hint_year)+": ");
		emailText.append(year + "\n");
		emailText.append(r.getString(R.string.offer_hint_sum)+": ");
		emailText.append(sum + "\n");
		emailText.append(r.getString(R.string.offer_hint_check)+": ");
		emailText.append(r.getString(offerCheckR)+"\n");
		emailText.append(r.getString(R.string.offer_hint_state)+": ");
		emailText.append(((Spinner) content.findViewById(R.id.offer_lot_state)).getSelectedItem().toString() + "\n");
		
		return emailText.toString();
		}
	

	private void showChoosePhotoDialog() 
		{
		final CharSequence[] items = getResources().getStringArray(R.array.offer_choose_photo_dialog_options);
		final AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
		
		builder.setTitle(R.string.offer_choose_photo_dialog_title);
		builder.setItems(items, new DialogInterface.OnClickListener() 
			{
			public void onClick(DialogInterface dialog, int which) 
				{
				switch (which) 
					{
					case 0:
						final Intent pick = new Intent(Intent.ACTION_GET_CONTENT);
						pick.setType("image/*");
						startActivityForResult(pick,IMAGE_CHOSEN);
						break;
						
					case 1:
						final Intent make = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
						make.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(new File(ctx.getFilesDir(),IMAGE_TMP_FILE)));
						startActivityForResult(make,PHOTO_TAKEN);
						break;
					}
				}
			});
		
		builder.create().show();
		}

	private Bitmap decodeFile(File f, boolean decodeForDisplayInPreview) 
		{
		Bitmap b = null;
		
		try 
			{
			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;

			FileInputStream fis = new FileInputStream(f);
			BitmapFactory.decodeStream(fis, null, o);
			fis.close();

			int scale = 1;
			int maxSize = decodeForDisplayInPreview ? IMAGE_MAX_SIZE : IMAGE_SEND_MAX_SIZE;
			if (o.outHeight > maxSize || o.outWidth > maxSize) 
				{
				scale = (int) Math.pow(
						2,
						(int) Math.round(Math.log(maxSize
								/ (double) Math.max(o.outHeight, o.outWidth))
								/ Math.log(0.5)));
				}

			BitmapFactory.Options o2 = new BitmapFactory.Options();
			o2.inSampleSize = scale;
			fis = new FileInputStream(f);
			b = BitmapFactory.decodeStream(fis, null, o2);
			fis.close();
			}
		catch (IOException e) {;}
		
		return b;
		}
	}
